package com.hm.cms.websit;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.hm.cms.def.JobboleTypeEnum;
import com.hm.cms.service.ArticleService;
import com.hm.cms.service.TermsService;
import com.hm.cms.util.WebSitUtil;
import com.hm.cms.vo.HcmsArticleVo;
import com.hm.cms.vo.HcmsTermsVo;
import com.hm.common.util.CommonUtil;
import com.hm.common.util.StringUtil;
import com.hm.common.util.WebUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @author shishun.wang
 * @date 2017年12月4日 上午10:43:38
 * @version 1.0
 * @describe 伯乐在线
 */
@Slf4j
@Component
public class JobboleHandler {
	
	private static int timeout = 3000000;

	@Autowired
	private TermsService termsService;

	@Autowired
	private ArticleService articleService;

	public void handler() {
		for (JobboleTypeEnum type : JobboleTypeEnum.values()) {
			mainDirectory(type.getTermTaxonomy(), type.getWebTag(), "1");
			WebSitUtil.wating3();
		}
	}

	public static void main(String[] args) throws Exception {
		String uri = "http://blog.jobbole.com/113076/";
		Document document = Jsoup.connect(uri).ignoreContentType(true)
				.userAgent("Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.15)").timeout(timeout).get();

		Elements titleEls = document.getElementsByTag("h1");
		if (CommonUtil.isEmpty(titleEls)) {
			return;
		}
		String title = titleEls.get(0).html();
		System.out.println(title);

		Elements contentEls = document.getElementsByClass("entry");
		if (CommonUtil.isEmpty(contentEls)) {
			return;
		}

		Element contentEl = contentEls.get(0);
		contentEl.getElementsByTag("div").remove();

		String content = contentEl.html();
		System.out.println(content);
	}

	private void loadArticle(String uri, String imgUri, String termTaxonomy, String operationUserId) {
		try {
			if (articleService.checkArticleSourceUri(uri)) {
				return;
			}

			Document document = Jsoup.connect(uri).ignoreContentType(true)
					.userAgent("Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.15)").timeout(timeout).get();

			Elements titleEls = document.getElementsByTag("h1");
			if (CommonUtil.isEmpty(titleEls)) {
				return;
			}
			String title = titleEls.get(0).html();
			System.out.println(title);

			String description = document.select("meta[name=description]").get(0).attr("content");
			Elements keywords = document.select("meta[name=keywords]");
			String keyStr = null;
			if(CommonUtil.isNotEmpty(keywords)) {
				keyStr = document.select("meta[name=keywords]").get(0).attr("content");
			}else {
				keyStr = title.trim();
			}
			System.out.println(description);
			System.out.println(keyStr);

			List<String> termIds = new ArrayList<String>();
			String[] keys = keyStr.split(",");
			for (String key : keys) {
				if (CommonUtil.isEmpty(key)) {
					continue;
				}
				HcmsTermsVo hcmsTermsVo = termsService.getHcmsTermsByTermName(key);
				if (CommonUtil.isNotEmpty(hcmsTermsVo)) {
					termIds.add(hcmsTermsVo.getId());
					continue;
				}

				HcmsTermsVo termsVo = new HcmsTermsVo();
				termsVo.setTermName(key);
				termsVo.setTermCode(key);
				termsVo.setTermOrder(-1);
				termIds.add(termsService.addTerms(termsVo, operationUserId));
			}

			Elements contentEls = document.getElementsByClass("entry");
			if (CommonUtil.isEmpty(contentEls)) {
				return;
			}

			Element contentEl = contentEls.get(0);
			contentEl.getElementsByTag("div").remove();

			String content = contentEl.html();

			if (StringUtil.isBlankOrNull(description)) {
				description = StringUtil.dislodgeAllBlank(WebUtil.clearHtmlTags(content.toString())).substring(0, 150);
			}

			HcmsArticleVo articleVo = new HcmsArticleVo();
			{
				articleVo.setTermIds(termIds);
				articleVo.setTermTayIds(Arrays.asList(termTaxonomy));
				articleVo.setArticleContent(content.toString());
				articleVo.setBreviaryIcon(imgUri);
				articleVo.setAuthorName("行者孙");
				articleVo.setReleaseTime(System.currentTimeMillis());
				articleVo.setTitle(title);
				articleVo.setKeywords(StringUtil.isBlankOrNull(keyStr) ? title : keyStr);
				articleVo.setSourceName("伯乐在线");
				articleVo.setSourceUri(uri);
				articleVo.setArticleOrder((int) articleService.getArtilcleMaxOrder());
				articleVo.setArticleExcerpt(description);
			}
			articleService.addArticle(articleVo, operationUserId);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}

	private void mainDirectory(String termTaxonomy, String uri, String operationUserId) {
		try {
			for(int page = 10;page >=1 ;page--) {
				Document document = Jsoup.connect(MessageFormat.format(uri, page)).ignoreContentType(true)
						.userAgent("Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.15)").get();

				Elements directoryEls = document.getElementsByClass("floated-thumb");
				for (Element directoryEl : directoryEls) {
					Elements els = directoryEl.getElementsByClass("post-thumb");
					if (CommonUtil.isEmpty(els)) {
						continue;
					}
					String articleImgUri = null;
					Elements articleImgLinkEls = els.get(0).getElementsByTag("img");
					if (CommonUtil.isNotEmpty(articleImgLinkEls)) {
						articleImgUri = articleImgLinkEls.get(0).attr("src");
					}
					Elements articleLinkEls = els.get(0).getElementsByTag("a");
					if (CommonUtil.isEmpty(els)) {
						continue;
					}
					String articleUrl = articleLinkEls.get(0).attr("href");

					System.out.println(articleImgUri);
					System.out.println(articleUrl);

					loadArticle(articleUrl, articleImgUri, termTaxonomy, operationUserId);
					WebSitUtil.wating3();
				}
			}
			WebSitUtil.wating3();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}
}
